package team2;

import java.util.Hashtable;
import java.util.List;

/**
 * Vector is a class that makes a vector from a body of text.
 * It uses the Tokenizer and Stemmer to construct the vector.
 * @author Brett Hlavinka
 */
public class Vector
{
    private Tokenizer tokenizer;
    private Stemmer stemmer;

    private Hashtable<String, Integer> vector;
    private double length;

    /**
     * Default constructor for a vector.
     * @param text The text that is used to construct the vector.
     */
    public Vector(String text)
    {
        //Make tokenizer and stemmer
        this.tokenizer = new Tokenizer();
        this.stemmer = new Stemmer();

        //Construct the vector
        List<String> tokens = tokenizer.tokenize(text);
        vector = new Hashtable<String, Integer>();
        for (String token : tokens)
        {
            String stem = stemmer.stem(token);
            if (vector.containsKey(stem))
            {
                Integer count = vector.get(stem);
                count++;
                vector.remove(stem);
                vector.put(stem, count);
            }
            else
            {
                vector.put(stem, 1);
            }
        }

        //Calculate length of vector
        int toBeSquareRooted = 0;
        for (Integer vectorComponent : vector.values())
        {
            toBeSquareRooted += (vectorComponent * vectorComponent);
        }
        length = Math.sqrt(toBeSquareRooted);
    }

    /**
     * Accessor method that gives the vector.
     * @return The Hashtable that is the vector.
     */
    public Hashtable<String, Integer> getVector()
    {
        return this.vector;
    }

    /**
     * Method that tells the length of the vector
     * @return A double that is the length of the vector.
     */
    public double getLength()
    {
        return this.length;
    }

    /**
     * Method that determines the similarity of this vector to the otherVector.
     * This is done by taking cosine of the angle between the vectors.
     * @param otherVector The other vector that this compares to.
     * @return A value from 0 to 1 where 1 is that highest similarity.
     */
    public double similarityWith(Vector otherVector)
    {
        int numerator = 0;
        for (String stem : vector.keySet())
        {
            if (otherVector.getVector().containsKey(stem))
            {
                numerator += (vector.get(stem) * otherVector.getVector().get(stem));
            }
        }
        int denominator = 1;
        denominator *= otherVector.getLength();
        denominator *= length;

        return numerator / denominator;
    }
}
